#include "sg_pic.h"
#include "../lcd_drivers/lcd.h"

inline void SgPic_init(sg_pic_t * this)
{
    memset(this, 0, sizeof(sg_pic_t));
}

void SgPic_setSource(sg_pic_t * this, u32 source)
{
    this->Source = source;
    this->Status = SG_ST_NORMAL;
    SgPic_refresh(this);
}

void SgPic_refresh(sg_pic_t * this)
{
    if(this->Status == SG_ST_NORMAL)
    {
        byte *buff = SG_MEM_ALLOC(_SG_DATA_BUFF_SIZE);
        u32 index = this->Source; // 指向待处理数据
        u32 remin_len = this->Height * this->Width * sizeof(lcd_color_t);    // 剩余的数据长度
        u32 per_len; // 本次处理长度

        // 锁定屏幕区域
        Lcd_SetWindow(this->Pos.x, this->Pos.y, this->Pos.x + this->Width - 1, this->Pos.y + this->Height - 1);

        while(remin_len > 0)
        {
            // 确定本次要处理的数据长度
            if(remin_len > _SG_DATA_BUFF_SIZE) per_len = _SG_DATA_BUFF_SIZE;
            else per_len = remin_len;
            // 读取数据到缓存
            _Sg_ReadSourceData(buff, index, per_len);
            // 写入到LCD
            while(Lcd_FillData(buff, per_len) == false);
            // 更新控制量
            remin_len -= per_len;
            index += per_len;
        }
        SG_MEM_FREE(buff);
    }
}

